package com.example.basics.config;

import com.example.basics.model.BaseResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(AppException.class)
    @ResponseBody
    public BaseResp customExceptionHandler(AppException e, HttpServletResponse servletResponse) {
        //此处e.getMessage()为null，因为没有定义message
        log.warn("app exception, {}", e.getMessage());
        String msg = e.getErrorDesc();
        servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new BaseResp(e.getErrorCode(), msg, null);
    }
}
